package com.sdkj.recruit.controller;


import java.io.IOException;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;

import org.apache.log4j.Logger;
import org.dozer.Mapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import com.sdkj.recruit.common.Constants;
import com.sdkj.recruit.model.ResultCode;
import com.sdkj.recruit.model.ResultData;
import com.sdkj.recruit.model.Resume;
import com.sdkj.recruit.model.SmsCode;
import com.sdkj.recruit.model.User;
import com.sdkj.recruit.model.WeixinConfig;
import com.sdkj.recruit.service.IUserService;
import com.sdkj.recruit.util.DESEncryption;
import com.sdkj.recruit.util.MD5Util;
import com.sdkj.recruit.util.RandomUtil;
import com.sdkj.recruit.util.StringUtil;
import com.sdkj.recruit.vo.UserVo;



@Controller
@Path("/login")
@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
public class LoginController {


	private static final Logger logger = Logger.getLogger(LoginController.class);
	@Autowired
	private Mapper mapper;

	@Autowired
	private IUserService userService;

	@POST
	@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
	@Path("/adminLogin")
	public UserVo adminLogin(@FormParam("userName") final String userName, @FormParam("password") final String password,
			@Context final HttpServletRequest request) {
		// 后台管理登陆时必须输入验证码
		final HttpSession session = request.getSession();
		String accessToken = MD5Util.string2MD5(userName + new Date().getTime());
		session.setMaxInactiveInterval(604800);// 设置session过期时间为1个小时，这里的以秒为单位的。
		Date lastLoginTime = new Date();
		
		User user = userService.queryUserByName(userName);
		
		/*User u =new User();
		u.setUserId(new RandomUtil().getRandomId());
		u.setUserName("admin");
		u.setPassword("4d31d5cec93bfcc47f103f0c1bc8a1a9");
		u.setUserType(1);
		List<User> uL =new ArrayList<>();
		uL.add(u);
		userService.saveUsers(uL);*/
		if (user == null) {
			return buildError(userName, 1, "用户不存在,请核对后输入");
		}
		
		if(user.getUserType()<1){
			return buildError(userName, 1, "该用户没有后台管理权限");
		}
		
		if(user.getAccountStatus()==1){
			return buildError(userName, 1, "用户已经停用");
		}
		String psw = generalPassword(userName, password);
		if (!psw.equals(user.getPassword())) {
			logger.info("Wrong password, " + userName + " login error.");
			return buildError(userName, 3, "用户名或者密码错误");
		}
		UserVo vo = mapper.map(user, UserVo.class);
		vo.setLastLoginTime(lastLoginTime);
		vo.setAuthenticated(true);
		vo.setAccessToken(accessToken);
		vo.setMenus(userService.getUserMeuns(user));
		// 记录登陆信息
		//userService.updateUserLoginInfo(accessToken,lastLoginTime,vo.getUserId());
		
		user =mapper.map(vo, User.class);
        session.setAttribute("showtimes_login", user);
		return vo;

	}
	
	
	
	
	/**
	 * 手机登录leida
	 * 
	 * @param userName
	 * @param password
	 * @param request
	 * @return
	 */
	@POST
	@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
	public ResultData<Object>  login( final UserVo userVo,@Context final HttpServletRequest request) {
		final HttpSession session = request.getSession();
		String accessToken = MD5Util.string2MD5(userVo.getMobile() + new Date().getTime());
		session.setMaxInactiveInterval(7776000*24*7);// 设置session过期时间为1个小时，这里的以秒为单位的。
		Date lastLoginTime = new Date();
		User user = userService.queryUserByPhone(userVo.getMobile());
		ResultData<Object> result =new ResultData<>();
		String userId =new RandomUtil().getRandomId();
		long expireTime =7776000;
		
		// 手机授权登录
		String uniqueId =userVo.getUniqueId();
		if(StringUtil.isNotEmptyString(uniqueId)) {
			
			WeixinConfig wf =userService.queryUserIsAuth(uniqueId);
			if(wf==null) {
				result.setResCode(ResultCode.FAILTURE_ERROR_CODE);
				result.setMsg("登录失败,用户不存在");
				return result;
			}
		}else {
			// 验证验证码
			SmsCode sms =userService.querySms(userVo.getMobile(),1);
			if(sms==null) {
				result.setResCode(ResultCode.FAILTURE_ERROR_CODE);
				result.setMsg("验证码不正确");
				return result;
			}
			if (!sms.getCode().equals(userVo.getCheckCode())) {
				result.setResCode(ResultCode.FAILTURE_ERROR_CODE);
				result.setMsg("验证码不正确");
				return result;
			}
		}
		
		if (user == null) {
			// 调用注册，写入用户信息
			user = new User();
			user.setUserName(userVo.getUserName());
			user.setUserId(userId);
			user.setMobile(userVo.getMobile());
			user.setCreateDate(new Date());
			user.setTokenTime(lastLoginTime);
			user.setLastLoginTime(lastLoginTime);
			user.setAccessToken(accessToken);
			user.setExpireTime(expireTime);
			user.setOnline(true);
			userService.register(user);
			session.setAttribute("recruit_login", user);
			return ResultCode.success("登录成功", user);
		} else {
			// 判断是否停用
			if(user.getAccountStatus()==1){
				result.setResCode(ResultCode.FAILTURE);
				result.setMsg("该用户已经停用");
				return result;
			}
			
			UserVo vo = mapper.map(user, UserVo.class);
			
			// 获取简历ID
			Resume resume =userService.queryResumeByUserId(vo.getUserId());
			if(resume!=null) {
				vo.setResumeId(resume.getResumeId());
			}
			vo.setLastLoginTime(lastLoginTime);
			vo.setMobile(userVo.getMobile());
			vo.setAuthenticated(true);
			vo.setAccessToken(accessToken);
			vo.setOnline(true);
			// 记录登陆信息
			userService.updateUserLoginInfo(accessToken, lastLoginTime,expireTime, vo.getUserId());
			user = mapper.map(vo, User.class);
			session.setAttribute("recruit_login", user);
			return ResultCode.success("登录成功", vo);
		}
	}
	

	/**
	 * 设置错误信息
	 * 
	 * @param userName
	 * @param errorCode
	 * @param errorMessage
	 * 
	 * @return
	 */
	private UserVo buildError(final String userName, final int errorCode, final String errorMessage) {

		final UserVo result = new UserVo();
		result.setAuthenticated(false);
		result.setErrorMessage(errorMessage);
		result.setErrorCode(errorCode);
		return result;
	}

	/**
	 * @param userName
	 * @param password
	 * @return
	 */
	private String generalPassword(final String userName, final String password) {
		String decryptStr = "";
		try {
			decryptStr = DESEncryption.decrypt(password, userName);
		} catch (IOException e) {
			logger.error("Error in decrypt. Reason: " + e.getMessage());
		} catch (Exception e) {
			logger.error("Error in decrypt. Reason: " + e.getMessage());
		}

		if (userName.indexOf("@") != -1) {
			String shortUserName = userName.substring(0, userName.indexOf("@"));
			return MD5Util.string2MD5(shortUserName.toLowerCase() + Constants.USER_KEY + MD5Util.string2MD5(decryptStr));
		} else {
			return MD5Util.string2MD5(userName.toLowerCase() + Constants.USER_KEY + MD5Util.string2MD5(decryptStr));
		}
	}
	
	
	public static void main(String[] args) {
		System.out.println(MD5Util.string2MD5("admin" + Constants.USER_KEY + MD5Util.string2MD5("showtimes@!~")));
	
		//4d31d5cec93bfcc47f103f0c1bc8a1a9
	}
	
	/**
	 * 退出登录
	 * @param request
	 * @return
	 */
	@GET
    @Path("/logout")
    public ResultData<Object> logout(@Context final HttpServletRequest request) {

		ResultData<Object> result =new ResultData<>();

        final HttpSession session = request.getSession();
        final User user = (User) session.getAttribute("showtimes_login");
        String userIosToken = null;
        String userId = null;
        if (user != null) {
            userId = user.getUserId();
        }
        logger.info("session user: " + user + "/" + userIosToken);

        userService.cleanUserLoginInfo(userId);
        session.setAttribute("recruit_login", null);
        
        session.invalidate();
        result.setResCode(ResultCode.SUCCESS);
		return result;
    }
	
	
	@GET
    @Path("/adminlogout")
    public ResultData<Object> adminlogout(@Context final HttpServletRequest request) {

		ResultData<Object> result =new ResultData<>();

        final HttpSession session = request.getSession();
        //final User user = (User) session.getAttribute("recruit_login");
        session.setAttribute("recruit_login", null);
        //删除redis 信息
        session.invalidate();
        result.setResCode(ResultCode.SUCCESS);
		return result;
    }

}
